package dev2dev.textclient.instruct;

import dev2dev.textclient.SipLayer;

import javax.sip.header.ToHeader;
import javax.sip.message.Request;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author jinbing.yao
 * @createTime 2023-10-26 11:24
 **/
public class HeartbeatProcess {
    public List<String> toList = new ArrayList<>();

    public SipLayer sipLayer;

    private int time = 6*1000;

    public  boolean sta = true;

    private Thread thread;

    public HeartbeatProcess(SipLayer sip) {
        super();
        sipLayer = sip;
        String from = "sip:" + sip.getUsername() + "@" + sip.getHost() + ":" + sip.getPort();
        toList.add(from);
    }
    //"sip:" + sipLayer.getUsername() + "@" + sipLayer.getHost() + ":" + sipLayer.getPort();
    public void addTo(String toInfo){
        if(toList.contains(toInfo)){return;}
        toList.add(toInfo);
    }

    //该方法一个仅调一次
    public void sendHeartbeat(){
        thread = new Thread(() -> {
            while (true){
                try {
                    Thread.sleep(time);
                    HashMap<String, String> map = new HashMap<>();
                    map.put("methodType", Request.OPTIONS);
//                    if(sipLayer.rtcrtpHeaderExample.audioSendSta){
//                        map.put("Allow", "INVITE, ACK, CANCEL, BYE, MESSAGE");
//                    }
                    for(String to : toList){
                        try {
                            sipLayer.sendMessage(to, new byte[0], map);
                        } catch (Throwable e) {
                            e.printStackTrace();
                            System.out.println("持续心跳失败");
                        }

                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();

    }
}
